package com.mamba.microservice.context;

import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Copyright ©2020 360jinrong All Rights Reserved
 * 请添加类/接口的说明：定义服务上下文
 *
 * @Package: com.mamba.microservice.context
 * @author: fangjin
 * @date: 2020年04月22日 11时27分
 */
@Setter
@Getter
public class ServiceContext {
    /**
     * 上下文的变量
     */
    private Map<String, String> contextVariables = new HashMap<>();

    private static final ThreadLocal<ServiceContext> context = new InheritableThreadLocal<ServiceContext>() {
        @Override
        protected ServiceContext childValue(ServiceContext parentValue) {
            ServiceContext serviceContext = new ServiceContext();
            if (parentValue != null) {
                serviceContext.initChildContext(parentValue);
            }
            return serviceContext;
        }

        @Override
        protected ServiceContext initialValue() {
            return new ServiceContext();
        }
    };

    public static ServiceContext getContext() {
        return context.get();
    }

    /**
     * 将父线程的上下文信息传递到子线程
     *
     * @param parentContext
     */
    private void initChildContext(ServiceContext parentContext) {
        if (parentContext == null || parentContext == this) {
            return;
        }
        contextVariables.clear();
        contextVariables.putAll(parentContext.getContextVariables());
    }

    /**
     * 获取生成的请求流水号
     *
     * @return
     */
    public String getRequestNo() {
        return contextVariables.get(ContextConstantKey.REQUEST_NO);
    }


    public void setRequestNo() {
        String requestNo = UUID.randomUUID().toString().replace("-", "");
        contextVariables.put(ContextConstantKey.REQUEST_NO, requestNo);
    }

    /**
     * 清除数据
     * 防止内存泄露
     */
    public void clearContextVariables() {
        contextVariables.clear();
    }
}
